package com.dapeis.service;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ag.core.exception.SysTipsException;
import com.ag.utils.DateUtils;
import com.ag.utils.NumberUtils;
import com.ag.utils.json.GsonUtils;
import com.dapeis.domain.CosFile;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;

/**
 * 腾讯COS上传文件 Title:COSFileService.java COSFileService Description:
 * 
 * @author yuanyong
 * @date 2017年5月1日 下午12:39:52 Email: hzyuanyong@126.com
 *
 */
@Service
public class COSFileService {

    @Resource
    CosFileObjectService cosFileObjectService;

    // 必须以该路径开头,否则会被springmvc拦截
    static final String COS_BASE_PATH = "/resources/";

    static final long appId = 1252470632;
    static final String secretId = "AKIDDIBvmVLOXWJwNfmhRzMWUcbOyc7QdP6a";
    static final String secretKey = "RinfLpX5RbaNyNabQ3WnvsfCFg1A7rPl";
    static final String bucketName = "stylist2017";

    public static final COSClient getCosClient() {
	ClientConfig clientConfig = new ClientConfig();
	clientConfig.setRegion("sh");
	Credentials cred = new Credentials(appId, secretId, secretKey);
	COSClient cosClient = new COSClient(clientConfig, cred);
	return cosClient;
    }

    /**
     * 存储数据返回列表ID
     * 
     * @param mulitpartFile
     * @param baseDir
     * @param request
     * @return
     */
    public String saveFileForId(MultipartFile mulitpartFile, String baseDir,
	    HttpServletRequest request) {
	String path = saveFile(mulitpartFile, baseDir, request);
	if (null != path) {
	    CosFile cosFile = new CosFile(path);
	    if (cosFileObjectService.insertSelective(cosFile) > 0) {
		return cosFile.getId().toString();
	    }
	}
	throw new SysTipsException("上传图片异常!");
    }

    /**
     * 上传网页文件
     * 
     * @param mulitpartFile
     * @param baseDir
     * @param request
     * @return
     */
    public String saveFile(MultipartFile mulitpartFile, String baseDir,
	    HttpServletRequest request) {
	try {
	    if (null == mulitpartFile || mulitpartFile.isEmpty()) {
		throw new SysTipsException("上传图片源异常!");
	    }
	    File tempFile = new File(request.getRealPath("/") + "temp/"
		    + DateUtils.nowDate(DateUtils.YYYYMMDDHHMMSS)
		    + mulitpartFile.getOriginalFilename());
	    mulitpartFile.transferTo(tempFile);
	    String remoteFilePathString = getUploadImgPath(mulitpartFile,
		    baseDir);
	    UploadFileRequest uploadFileRequest = new UploadFileRequest(
		    bucketName, remoteFilePathString, tempFile.getPath());
	    uploadFileRequest.setEnableShaDigest(false);
	    String result = getCosClient().uploadFile(uploadFileRequest);
	    System.out.println("result:" + result);
	    String resultCode = GsonUtils.getDeepValue(result, "code");
	    if (StringUtils.equals(resultCode, "0")) {
		tempFile.deleteOnExit();
		return remoteFilePathString;
	    }

	} catch (IllegalStateException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	throw new SysTipsException("上传图片异常!");
    }

    /**
     * 上传文件
     * 
     * @param file
     * @param baseDir
     * @return
     */
    public String saveFile(File file, String baseDir) {
	try {
	    if (file == null || file.length() == 0) {
		return null;
	    }
	    String remoteFilePathString = getUploadImgPath(file, baseDir);
	    UploadFileRequest uploadFileRequest = new UploadFileRequest(
		    bucketName, remoteFilePathString, file.getPath());
	    uploadFileRequest.setEnableShaDigest(false);
	    String result = getCosClient().uploadFile(uploadFileRequest);
	    System.out.println("result:" + result);
	    String resultCode = GsonUtils.getDeepValue(result, "code");
	    if (StringUtils.equals(resultCode, "0")) {
		file.deleteOnExit();
		return remoteFilePathString;
	    }

	} catch (IllegalStateException e) {
	    e.printStackTrace();
	}
	return null;
    }

    /**
     * 删除文件
     * 
     * @param filePath
     * @return
     */
    public boolean delete(String filePath) {

	return false;
    }

    public String getUploadImgPath(MultipartFile file, String baseDir) {
	String rootPath = "/resources/" + baseDir + "/";
	String relativelyPath = rootPath
		+ DateUtils.nowDate(DateUtils.YYYYMMDDHHMMSS)
		+ NumberUtils.random() + "."
		+ FilenameUtils.getExtension(file.getOriginalFilename());

	return relativelyPath;
    }

    public String getUploadImgPath(File file, String baseDir) {
	String rootPath = "/resources/" + baseDir + "/";
	String relativelyPath = rootPath
		+ DateUtils.nowDate(DateUtils.YYYYMMDDHHMMSS)
		+ NumberUtils.random() + getFileOriginName(file);

	return relativelyPath;
    }

    /**
     * aa.saa.jpg
     * 
     * @param file
     * @return .jpg
     */
    String getFileOriginName(File file) {
	String fileName = file.getName();
	return fileName.substring(fileName.lastIndexOf("."), fileName.length());
    }
}
